<?php

namespace app\backend\controller\admin;

use app\backend\logic\Admin as AdminLogic;
use app\backend\model\Admin as AdminModel;
use app\backend\model\Role;
use surface\form\components\Hidden;
use surface\form\components\Input;
use surface\form\components\Select;
use surface\form\components\Switcher;
use surface\form\components\Upload;
use surface\helper\FormAbstract;

class Form extends FormAbstract
{

    public function columns(): array
    {
        $roles = [];
        $id = input('id', '');
        $model = $id ? AdminModel::find($id) : new AdminModel();
        if ( ! $model->isEmpty())
        {
            $exists = false;
            $rolesList = $model->role;
            foreach ($rolesList as $g)
            {
                $roles[] = $g['id'];
            }
        } else
        {
            $exists = true;
        }

        return array_merge(
            [
                (new Input('username', AdminModel::$labels['username'], $model->username ?? ''))->validate(
                    [
                        [
                            'required' => 'true',
                            'message'  => AdminModel::$labels['username'] . '不能为空',
                        ],
                    ]
                ),
                new Upload('avatar', AdminModel::$labels['avatar'], $model->avatar ?? ''),
                new Switcher('status', AdminModel::$labels['status'], $model->status ?? ''),
                new Input('nickname', AdminModel::$labels['nickname'], $model->nickname ?? ''),
                (new Input('password', AdminModel::$labels['password'], ''))->marker('不填写不会更改密码'),
                (new Select('roles', AdminModel::$labels['roles'], count($roles) > 0 ? $roles : ''))
                    ->props(['multiple' => true])
                    ->options(formatOptions(Role::getCanList())),
            ], $exists ? [new Hidden('id',  $model->id ?? null)] : []
        );
    }

    public function save(): bool
    {
        $post = request()->only(['username', 'status', 'nickname', 'password', 'roles', 'id', 'avatar']);
        $roles = [];
        if (isset($post['roles']))
        {
            $roles = $post['roles'];
            unset($post['roles']);
        }

        return AdminLogic::save($post, (array)$roles);
    }

}
